package com.potevio.simulator.strategy.impl;


import com.potevio.simulator.common.CommonFlag;
import com.potevio.simulator.common.GetHexMessage;
import com.potevio.simulator.common.MsgBean;
import com.potevio.simulator.config.MsgTypeConst;
import com.potevio.simulator.heart.HeartbeatClient;
import com.potevio.simulator.init.ApplicationStartQuartzJobListener;
import com.potevio.simulator.strategy.ReceiveMsgStrategy;
import com.potevio.simulator.task.ChargeMsgTask;
import com.potevio.simulator.util.CommFunction;
import com.potevio.simulator.util.HexUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.ScheduledFuture;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName Receive6C
 * @Description: 接收6C报文
 * @Date 2021/6/1  10:27
 * @Author zyd
 */
public class Receive6CCommand implements ReceiveMsgStrategy {

    @Override
    public void receiveMessage(ChannelHandlerContext ctx, Map<String, LinkedHashMap<String, String>> resultHexMap, String revertCommandCode) throws Exception {
        HeartbeatClient.chargeType = "0";
        if("3.4".equals(CommonFlag.version)){

            MsgTypeConst.chm_Map.put("0x6C", resultHexMap.get(revertCommandCode));
            // 回复7A报文
            Map<String, LinkedHashMap<String, String>> map7A = new GetHexMessage().getDataDomain(MsgTypeConst.CENTER_LEGAL_USER_AUTH_MSG);
            // 处理7A报文，从6C中获取对应字段值
            map7A.put("0x7A", deal7A(map7A.get("0x7A")));
            // 设置全局初始电表度数
            ChargeMsgTask.InitMeterDegrees = HexUtil.makeRandom(100f, 0f, 0).intValue();
            ctx.channel().writeAndFlush(map7A);
        }else {
            String chargePort = resultHexMap.get("6C").get("chargePort");
            MsgTypeConst.chm_Map.put("0x" + revertCommandCode + "_" + chargePort, resultHexMap.get(revertCommandCode));
            // 正在充电集合加入当前枪号
            MsgTypeConst.CHARGE_POSTS.add(chargePort);
            Collections.sort(MsgTypeConst.CHARGE_POSTS);
            // 回复7A报文
            Map<String, LinkedHashMap<String, String>> map = new GetHexMessage().getDataDomain(MsgTypeConst.CENTER_LEGAL_USER_AUTH_MSG, chargePort);
            // 处理7A报文，从6C中获取对应字段值
            map.put("0x7A", deal7A(map.get("0x7A"), chargePort));
            // 设置全局初始电表度数
            ChargeMsgTask.InitMeterDegrees = HexUtil.makeRandom(100f, 0f, 0).intValue();
            ctx.channel().writeAndFlush(map);
            // 开启远端充电过程报文定时任务
            ChargeMsgTask chargeMsgTask = new ChargeMsgTask();
//            ScheduledFuture<?> scheduledFuture = ctx.channel().eventLoop().scheduleAtFixedRate(chargeMsgTask, 0, HeartbeatClient.chargeMsgInterval, TimeUnit.SECONDS);
//            // 每个枪号启动自己的定时充电任务
//            HeartbeatClient.chargeMsgTaskFutureMaps.put(chargePort, scheduledFuture);
        }


        // 设置充电桩状态为充电中
        HeartbeatClient.chargingPileState = 1;
    }

    /**
     * 处理7A报文
     *
     * @param map
     * @return
     */
    public LinkedHashMap<String, String> deal7A(LinkedHashMap<String, String> map) {
        LinkedHashMap<String, MsgBean> msgBeanMap = new LinkedHashMap<String, MsgBean>();
        String commandCode = "";
        Set<String> keySet = map.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String fieldName = iterator.next();
            String fieldValue = map.get(fieldName);
            // 命令代码
            if ("commandCode".equals(fieldName)) {
                commandCode = fieldValue;
                msgBeanMap = ApplicationStartQuartzJobListener.chm.get(commandCode);
            }
            if (StringUtils.isBlank(fieldValue)) {
                fieldValue = MsgTypeConst.chm_Map.get("0x6C").get(fieldName);
                if (fieldValue != null && fieldValue.length() > 0) {
                    // 字段属性实体类
                    MsgBean msgBean = msgBeanMap.get(fieldName);
                    // 返回报文的字段值长度
                    int revertFieldLength = fieldValue.length() / 2;
                    // 全局变量中的字段长度
                    int msgFieldLength = Integer.valueOf(msgBean.getLength());
                    if (revertFieldLength < msgFieldLength) {
                        // 计算两个字段长度相差字节数，为了补0
                        int num = msgFieldLength - revertFieldLength;
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int j = 0; j < num * 2; j++) {
                            stringBuffer.append("0");
                        }
                        fieldValue = fieldValue + stringBuffer;
                    }
                }
                MsgTypeConst.chm_Map.get("0x7A").put(fieldName, fieldValue);
                map.put(fieldName, fieldValue);
            }
        }
        return map;
    }


    /**
     * 处理7A报文  3.4a
     *
     * @param map
     * @return
     */
    public LinkedHashMap<String, String> deal7A(LinkedHashMap<String, String> map, String chargePort) {
        LinkedHashMap<String, MsgBean> msgBeanMap = new LinkedHashMap<String, MsgBean>();
        String commandCode = "";
        Set<String> keySet = map.keySet();
        Iterator<String> iterator = keySet.iterator();
        while (iterator.hasNext()) {
            String fieldName = iterator.next();
            String fieldValue = map.get(fieldName);
            // 命令代码
            if ("commandCode".equals(fieldName)) {
                commandCode = fieldValue;
                msgBeanMap = ApplicationStartQuartzJobListener.chm.get(commandCode);
            }
            // 命令代码
            if (StringUtils.isBlank(fieldValue)) {
                fieldValue = MsgTypeConst.chm_Map.get("0x6C_" + chargePort).get(fieldName);
                if (fieldValue != null && fieldValue.length() > 0) {
                    // 字段属性实体类
                    MsgBean msgBean = msgBeanMap.get(fieldName);
                    // 返回报文的字段值长度
                    int revertFieldLength = fieldValue.length() / 2;
                    // 全局变量中的字段长度
                    int msgFieldLength = Integer.valueOf(msgBean.getLength());
                    if (revertFieldLength < msgFieldLength) {
                        // 计算两个字段长度相差字节数，为了补0
                        int num = msgFieldLength - revertFieldLength;
                        StringBuffer stringBuffer = new StringBuffer();
                        for (int j = 0; j < num * 2; j++) {
                            stringBuffer.append("0");
                        }
                        fieldValue = fieldValue + stringBuffer;
                    }
                }
                MsgTypeConst.chm_Map.get("0x7A_" + chargePort).put(fieldName, fieldValue);
                map.put(fieldName, fieldValue);
            }
        }
        return map;
    }
}
